package com.leyou.gateway.filters;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Configuration
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProps;
    @Autowired
    private FilterProperties filterProps;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 判断是否启用拦截，true 启用   false 不启用
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();

        String requestURI = request.getRequestURI();
        List<String> allowPaths = filterProps.getAllowPaths();
        for (String allowPath : allowPaths) {
            if (requestURI.startsWith(allowPath)) {
                return false;
            }

        }
        return true;
    }

    /**
     * 拦截的具体业务，如果说什么都没做就是放行，如果要拦截则要说明一下
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        //获取当前的上下文
        RequestContext context = RequestContext.getCurrentContext();

        HttpServletRequest request = context.getRequest();


        try {
            //解析cookie 如果可以解析则放行，否则拦截
            String token = CookieUtils.getCookieValue(request, jwtProps.getCookieName());

            //解析token
            JwtUtils.getInfoFromToken(token, jwtProps.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            //出问题了 要拦截，就是不放行，不响应
            context.setSendZuulResponse(false);//不响应
            context.setResponseStatusCode(401);//同时给一个状态码 401  告诉对方未授权
        }

        return null;
    }
}
